﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Web.Script.Serialization;


namespace CCPSIP
{
    /// <summary>CCPSIP_007：取得 IP PBX 登入資訊 API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。

    public class user_info : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】取得POST參數
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string UserLocale = req.Form["UserLocale"];//【To-Do】記錄User語言環境
                string appVersion = AppleKit.GetAppVersion(req.UserAgent);

                //【02】驗證身分
                //
                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);

                if (userInfo == null)
                {
                    if (OracleKitUser.hasValidIdHeader(idHeader))
                        throw new Exception("ERROR_01A: Please check your system clock");//請檢查系統時鐘
                    else
                        throw new Exception("ERROR_01B: Cannot identify this device");//無法識別此裝置
                }
                else
                {
                    //Record iSender user app version now.
                    if (userInfo.DeviceType.Equals("Android"))
                    {
                        string ipAddress = AppleKit.GetIPAddress(req);
                        AppleKit.insertAndroid_AppLog(@"Login", "com.ccp.sipphone", appVersion, userInfo.SIP_Num, ipAddress, req.UserAgent);
                    }
                    else if (userInfo.DeviceType.Contains("iPhone") ||
                        userInfo.DeviceType.Contains("iPad") ||
                        userInfo.DeviceType.Contains("iPod"))
                    {
                        //insert IOS_APP_LOG Table
                        AppleKit.insertAppLog(@"iSender", appVersion, req, userInfo);
                    }
                }

                Dictionary<string, string> resultDict = new Dictionary<string, string>();
                resultDict["USER_TYPE"] = userInfo.UserType;
                resultDict["SIP_NO"] = userInfo.SIP_Num;


                //【03】取得 IP PBX 帳號資訊
                //
                Dictionary<string, string> paramDict = IPPbxKitV3.GetUserData(userInfo.SIP_Num);
                resultDict["DTMF"] = paramDict["dtmf"].ToUpper();
                if (paramDict["tls"].ToLower() == "yes")
                {
                    resultDict["SIP_SERVER"] = "118.163.125.205";//TLS不用Port號
                    resultDict["PROTOCOL"] = "TLS";
                }
                else
                {
                    resultDict["SIP_SERVER"] = "118.163.125.205:1352";
                    resultDict["PROTOCOL"] = "UDP";
                }


                //【04】取得密碼相關資訊
                //
                SipSecretRule ruleObj = SipKit.getSipSecretRule(userInfo.SIP_Num);
                if (ruleObj == null)
                {
                    throw new Exception("Error_02: NO_SIP_SETTING");
                }
                resultDict["HASH_TYPE"] = ruleObj.HashType;
                resultDict["HASH_START"] = ruleObj.HashStart.ToString();
                resultDict["HASH_LEN"] = ruleObj.HashLength.ToString();


                //【98】記錄最新登入時間
                //
                OracleKitUser.UpdateLoginTime(userInfo.SIP_Num);

                //【99】回傳登入資訊
                //
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = ChrisKit.DictToJSON(resultDict);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
